import { Button, Checkbox, Container, Group, Pagination, Table, Modal, Text, TextInput, NumberInput } from "@mantine/core";
import { useEffect, useState } from "react";
import axios from "axios";
import { notifications } from '@mantine/notifications';
import { modals } from '@mantine/modals';

// 首先定义一个接口描述PC的数据结构
interface PC {
    id: number;
    pc_name: string;
    pc_brand: string;
    pc_price: number;
    neicun_rongliang: number;
    yingpan_rongliang: number;
    graph_device: string;
    screen_size: string;
    screen_resolution: string;
}

function HomePage() {
    const [selectedRows, setSelectedRows] = useState<number[]>([]);
    const [pcList, setPCList] = useState<PC[]>([]);
    const [pageInfo, setPageInfo] = useState<any>();
    const [detailsModalOpen, setDetailsModalOpen] = useState(false);
    const [currentPC, setCurrentPC] = useState<any>(null);
    const [editModalOpen, setEditModalOpen] = useState(false);
    const [editingPC, setEditingPC] = useState<any>(null);

    useEffect(() => {
        getPCInfo({ page: 1, per_page: 10 })
    }, [])

    const getPCInfo = (condition: any) => {
        axios.get("/app-api/get-pcs", { params: condition }).then((res) => {
            setPCList(res.data.pcs)
            setPageInfo(res.data.pagination)
        })
    }

    const handleViewDetails = (pc: any) => {
        setCurrentPC(pc);
        setDetailsModalOpen(true);
    };

    const handleEdit = (pc: any) => {
        setEditingPC({
            id: pc.id,
            pc_name: pc.pc_name,
            brand: pc.brand,
            pc_price: pc.pc_price,
            neicun_rongliang: pc.neicun_rongliang,
            yingpan_rongliang: pc.yingpan_rongliang,
            graph_device: pc.graph_device,
            screen_size: pc.screen_size,
            resolution: pc.resolution
        });
        setEditModalOpen(true);
    };

    const handleSaveEdit = () => {
        axios.put(`/app-api/update-pc/${editingPC.id}`, editingPC)
            .then(() => {
                setPCList(pcList.map((pc: any) =>
                    pc.id === editingPC.id ? editingPC : pc
                ));
                setEditModalOpen(false);
                notifications.show({
                    title: '修改成功',
                    message: '记录已成功更新',
                    color: 'green',
                });
            })
            .catch((error) => {
                notifications.show({
                    title: '修改失败',
                    message: '更新记录时发生错误',
                    color: 'red',
                });
            });
    };

    const handleDelete = (pcId: number) => {
        modals.openConfirmModal({
            title: '确认删除',
            centered: true,
            children: (
                <Text size="sm">
                    您确定要删除这条记录吗？此操作不可撤销。
                </Text>
            ),
            labels: { confirm: '确认删除', cancel: '取消' },
            confirmProps: { color: 'red' },
            cancelProps: { color: 'gray' },
            onConfirm: () => {
                axios.delete(`/app-api/delete-pc/${pcId}`).then(() => {
                    setPCList(pcList.filter((pc: any) => pc.id !== pcId));
                    notifications.show({
                        title: '删除成功',
                        message: '记录已成功删除',
                        color: 'green',
                    });
                });
            },
        });
    };

    const rows = pcList.map((element: any) => (
        <Table.Tr
            key={element.id}
            bg={selectedRows.includes(element.id) ? 'var(--mantine-color-blue-light)' : undefined}
        >
            <Table.Td>{element.pc_name}</Table.Td>
            <Table.Td>{element.pc_brand}</Table.Td>
            <Table.Td>{element.pc_price}</Table.Td>
            <Table.Td>{element.neicun_rongliang}G</Table.Td>
            <Table.Td>{element.yingpan_rongliang}G</Table.Td>
            <Table.Td>{element.graph_device}</Table.Td>
            <Table.Td>{element.screen_size}</Table.Td>
            <Table.Td>{element.screen_resolution}</Table.Td>
            <Table.Td>
                <Group gap={4} className="w-full flex justify-center items-center">
                    <Button size={'xs'} color={'green'} onClick={() => handleViewDetails(element)}>详情</Button>
                    {(localStorage.getItem('user_role') as string) == '0' && <Button size={'xs'} onClick={() => handleEdit(element)}>编辑</Button>}
                    {(localStorage.getItem('user_role') as string) == '0' && <Button size={'xs'} color={'red'} onClick={() => handleDelete(element.id)}>删除</Button>}
                </Group>
            </Table.Td>
        </Table.Tr>
    ));

    return (
        <div className={'mx-[unset]'}>
            <div></div>
            <div className={'py-[10px]'}>
                <Table.ScrollContainer minWidth={500}>
                </Table.ScrollContainer>
                <Table withTableBorder withColumnBorders stickyHeader>
                    <Table.Thead>
                        <Table.Tr>
                            <Table.Th align={'center'} className={"w-[200px]"}>
                                <div className={'w-full flex justify-center'}>名称</div>
                            </Table.Th>
                            <Table.Th align={'center'} className={'align-middle'}>品牌</Table.Th>
                            <Table.Th>价格</Table.Th>
                            <Table.Th className={"w-[100px]"}>内存</Table.Th>
                            <Table.Th>硬盘</Table.Th>
                            <Table.Th>显卡</Table.Th>
                            <Table.Th className={"w-[100px]"}>屏幕尺寸</Table.Th>
                            <Table.Th>分辨率</Table.Th>
                            <Table.Th className={"w-[200px]"}>
                                <div className="w-full flex justify-center items-center">
                                    操作
                                </div>
                            </Table.Th>
                        </Table.Tr>
                    </Table.Thead>
                    <Table.Tbody>{rows}</Table.Tbody>
                </Table>
            </div>
            <div className={'py-[10px]'}>
                {
                    pageInfo && (
                        <Pagination total={pageInfo.pages as any} onPreviousPage={() => {
                            if (pageInfo.has_prev) {
                                getPCInfo({ page: pageInfo.prev_num, per_page: pageInfo.per_page })
                            }
                        }} onNextPage={() => {
                            if (pageInfo.has_next) {
                                getPCInfo({ page: pageInfo.next_num, per_page: pageInfo.per_page })
                            }
                        }} onChange={(page: number) => {
                            getPCInfo({ page: page, per_page: pageInfo.per_page })
                        }} />
                    )
                }
            </div>
            <Modal
                opened={editModalOpen}
                onClose={() => setEditModalOpen(false)}
                title="修改电脑信息"
                size="lg"
            >
                {editingPC && (
                    <div className="space-y-4">
                        <TextInput
                            label="名称"
                            value={editingPC.pc_name}
                            onChange={(e) => setEditingPC({
                                ...editingPC,
                                pc_name: e.target.value
                            })}
                        />
                        <TextInput
                            label="品牌"
                            value={editingPC.brand}
                            onChange={(e) => setEditingPC({
                                ...editingPC,
                                brand: e.target.value
                            })}
                        />
                        <NumberInput
                            label="价格"
                            value={editingPC.pc_price}
                            onChange={(value) => setEditingPC({
                                ...editingPC,
                                pc_price: value
                            })}
                            decimalScale={2}
                            min={0}
                        />
                        <NumberInput
                            label="内存容量(G)"
                            value={editingPC.neicun_rongliang}
                            onChange={(value) => setEditingPC({
                                ...editingPC,
                                neicun_rongliang: value
                            })}
                            min={0}
                        />
                        <NumberInput
                            label="硬盘容量(G)"
                            value={editingPC.yingpan_rongliang}
                            onChange={(value) => setEditingPC({
                                ...editingPC,
                                yingpan_rongliang: value
                            })}
                            min={0}
                        />
                        <TextInput
                            label="显卡"
                            value={editingPC.graphics_card}
                            onChange={(e) => setEditingPC({
                                ...editingPC,
                                graphics_card: e.target.value
                            })}
                        />
                        <TextInput
                            label="屏幕尺寸"
                            value={editingPC.screen_size}
                            onChange={(e) => setEditingPC({
                                ...editingPC,
                                screen_size: e.target.value
                            })}
                        />
                        <TextInput
                            label="分辨率"
                            value={editingPC.resolution}
                            onChange={(e) => setEditingPC({
                                ...editingPC,
                                resolution: e.target.value
                            })}
                        />
                        <Group justify="flex-end" mt="md">
                            <Button variant="light" onClick={() => setEditModalOpen(false)}>取消</Button>
                            <Button onClick={handleSaveEdit}>保存</Button>
                        </Group>
                    </div>
                )}
            </Modal>
            <Modal opened={detailsModalOpen} onClose={() => setDetailsModalOpen(false)} title="PC Details">
                {currentPC && (
                    <div className="space-y-2">
                        <p>名称: {currentPC.pc_name}</p>
                        <p>品牌: {currentPC.pc_brand}</p>
                        <p>价格: {currentPC.pc_price}元</p>
                        <p>CPU系列: {currentPC.cpu_xilie}</p>
                        <p>CPU型号: {currentPC.cpu_xinghao}</p>
                        <p>CPU核心数: {currentPC.cpu_hexinshu}</p>
                        <p>CPU缓存: {currentPC.cpu_huancun}</p>
                        <p>CPU睿频: {currentPC.cpu_ruipin}</p>
                        <p>内存: {currentPC.neicun_rongliang}G {currentPC.neicun_leixing}</p>
                        <p>硬盘: {currentPC.yingpan_rongliang}G {currentPC.yingpan_miaoshu}</p>
                        <p>显卡: {currentPC.graph_device || '集成显卡'}</p>
                        <p>屏幕尺寸: {currentPC.screen_size}英寸</p>
                        <p>分辨率: {currentPC.screen_resolution}</p>
                    </div>
                )}
            </Modal>
        </div>
    )
}

const PCChatTable = (props: { pcs: any }) => {
    const { pcs } = props;
    const [detailsModalOpen, setDetailsModalOpen] = useState(false);
    const [currentPC, setCurrentPC] = useState<any>();
    const handleDetailsClick = (pc: any) => {
        setCurrentPC(pc);
        setDetailsModalOpen(true);
    };
    return (
        <>
            <Modal opened={detailsModalOpen} onClose={() => setDetailsModalOpen(false)} title="PC Details">
                {currentPC && (
                    <div className="space-y-2">
                        <p>名称: {currentPC.pc_name}</p>
                        <p>品牌: {currentPC.pc_brand}</p>
                        <p>价格: {currentPC.pc_price}元</p>
                        <p>CPU系列: {currentPC.cpu_xilie}</p>
                        <p>CPU型号: {currentPC.cpu_xinghao}</p>
                        <p>CPU核心数: {currentPC.cpu_hexinshu}</p>
                        <p>CPU缓存: {currentPC.cpu_huancun}</p>
                        <p>CPU睿频: {currentPC.cpu_ruipin}</p>
                        <p>内存: {currentPC.neicun_rongliang}G {currentPC.neicun_leixing}</p>
                        <p>硬盘: {currentPC.yingpan_rongliang}G {currentPC.yingpan_miaoshu}</p>
                        <p>显卡: {currentPC.graph_device || '集成显卡'}</p>
                        <p>屏幕尺寸: {currentPC.screen_size}英寸</p>
                        <p>分辨率: {currentPC.screen_resolution}</p>
                    </div>
                )}
            </Modal>
            <Table verticalSpacing="xs" highlightOnHover striped withColumnBorders
                styles={{
                    thead: {
                        '& tr': {
                            backgroundColor: '#007bff',
                            color: 'white'
                        },
                        '& th': {
                            borderBottom: '2px solid #e0e0e0'
                        }
                    },
                    tbody: {
                        '& tr': {
                            '&:nth-of-type(even)': {
                                backgroundColor: '#f8f9fa'
                            },
                            '&:hover': {
                                backgroundColor: '#e9ecef'
                            }
                        }
                    },
                    td: {
                        border: '1px solid #f0f0f0'
                    }
                }}>
                <Table.Thead>
                    <Table.Tr>
                        <Table.Th>名称</Table.Th>
                        <Table.Th>品牌</Table.Th>
                        <Table.Th>价格</Table.Th>
                        <Table.Th>显卡</Table.Th>
                    </Table.Tr>
                </Table.Thead>
                <Table.Tbody>
                    {pcs.map((pc: any, index: any) => {
                        return (
                            <Table.Tr key={index}>
                                <Table.Td>{pc.pc_name}</Table.Td>
                                <Table.Td>{pc.pc_brand}</Table.Td>
                                <Table.Td>{pc.pc_price}￥</Table.Td>
                                <Table.Td>{pc.graph_device}</Table.Td>
                                <Table.Td>
                                    <Group>
                                        <Button onClick={() => handleDetailsClick(pc)}>详情</Button>
                                        <Button color="green" onClick={() => { window.open(pc.url, '_blank') }}>网站</Button>
                                    </Group>
                                </Table.Td>
                            </Table.Tr>
                        )
                    })}
                </Table.Tbody>
            </Table>
        </>
    )
}

export { HomePage, PCChatTable };
